import json

import requests
from urllib import parse
from requests.utils import cookiejar_from_dict, dict_from_cookiejar
import http.cookiejar as cookielib
from logging_config import get_logger


def parser_query(base_url):
    parse_result = parse.urlparse(base_url)
    query = parse_result.query
    if query:
        dict_query = dict(parse.parse_qsl(query))
        return dict_query
    return {}


headers_base = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"
}


class RequestCookiesHandler:
    def __init__(self, session: requests.Session, cookies_filename="cookies.txt"):
        self.session = session
        self.logger = get_logger()
        self.cookies = cookielib.LWPCookieJar(filename=cookies_filename)

    def load_cookies(self):
        try:
            self.cookies.load(ignore_discard=True, ignore_expires=True)
            load_cookies = dict_from_cookiejar(self.cookies)
            self.session.cookies = cookiejar_from_dict(load_cookies)
        except Exception as e:
            self.logger.warn(e)

    def save_cookie(self):
        cookiejar_from_dict({c.name: c.value for c in self.session.cookies}, self.cookies)
        self.cookies.save(ignore_discard=True, ignore_expires=True)

    def cookies_to_tk(self, cookie_key="MMAD_TICKET"):
        b = self.session.cookies.get(cookie_key, domain=".a.weixin.qq.com")
        if b is None:
            b = self.session.cookies.get(cookie_key, "", domain="")
        t = 5381
        for i in b:
            t += (t << 5) + ord(i)
        return 2147483647 & t


def save_file(data, path='detail.json'):
    with open(path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False)
